#include "../include/BST.h"
#include "../include/errorcodes.h"


void copyFile(char *source_file_path, char *dest_file_path) {

	int souceBlockNo, destBlockNo, file_offset=0, size=0, i=0;
	char ch='0', readChars;

	fd *sourceFile = bstSearchNode(&bstRoot, source_file_path);
	
	if(sourceFile == NULL) {
		printf("copyfile_FAILURE %s\n", ERR_VFS_COPYFILE_01);
		return;
	}

	char *destPath = parsePath(dest_file_path);
	fd *destFile = bstSearchNode(&bstRoot, destPath);
	
	if(destFile == NULL) {
		printf("copyfile_FAILURE %s\n", ERR_VFS_COPYFILE_02);
		return;
	}

	if(sourceFile->fileType == 'D') {
		printf("copyfile_FAILURE %s\n", ERR_VFS_COPYFILE_03);
		return;
	}

	destFile = bstSearchNode(&bstRoot, dest_file_path);

	if(destFile == NULL) {

		if(fdcounter >= header.maxNoOfFileDescriptor) {
			printf("copyfile_FAILURE %s \n", ERR_VFS_COPYFILE_04);
			return;
		}

		char *fileName = fetchFileName(dest_file_path);

		add_for_copyFile(destPath, fileName, source_file_path);

		
	}
	else {

		souceBlockNo = sourceFile->blockNum;
		destBlockNo = destFile->blockNum;
	
		FILE *fptr=fopen(header.fileSystemLabel,"rb+");
		char content[1024];

		if(fptr==NULL) {
			printf("copyfile_FAILURE %s \n", ERR_VFS_MOUNT_02);
			return;
		}
		else {
			while(ch!='!') {
				fread(&ch,sizeof(ch),1,fptr);
				file_offset++;
			}

			fseek(fptr,(file_offset+(souceBlockNo*1024)),SEEK_SET);
		
			while((readChars = fgetc(fptr)) != EOF) {
				content[i] = readChars;
				i++;
				//fputc(readChars, destPtr);
			}
	
			size = i;
			i=0;
			char blank=' ';
			//printf("\n**********************************\n");
			fseek(fptr,(file_offset+(destBlockNo*1024)),SEEK_SET);
			while(i<1024) {
				fputc(blank, fptr);
				i++;
			}
			i=0;

			fseek(fptr,(file_offset+(destBlockNo*1024)),SEEK_SET);
			while(i<size) {
				//printf("%c", content[i]);
				fputc(content[i], fptr);
				i++;
			}
			fputc(EOF, fptr);
			//printf("\n*********************************\n");

			i=0;
			fseek(fptr,(file_offset+(destBlockNo*1024)),SEEK_SET);

			/*while(i<size) {
				printf("%c", fgetc(fptr));
				i++;
			}*/

		}
	
		fclose(fptr);
		}
		printf("copyfile_SUCCESS\n");
	}	

